<script setup>
import { onMounted, ref, watch } from 'vue'
import { queryAllApi, saveApi, queryByIdApi, updateApi, deleteApi } from '@/api/emp'
import { queryAllApi as queryAllDeptApi } from '@/api/dept'
import { ElMessage, ElMessageBox } from 'element-plus'

const searchEmp = ref({
  name: '',
  gender: '',
  entryDate: [],
  begin: '',
  end: ''
})

const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

/* watch侦听语法
const a = ref('')
watch(a, (newVal, oldVal) => {
  console.log(`数据源发生了变化，变化后的值：${newVal}, 变化前的值：${oldVal}`);
})
侦听对象的单个属性
const user = ref({name: '', age: 10})
watch(() => user.value.name, (newVal, oldVal) => {
  console.log(`数据源发生了变化，变化后的值：${newVal}, 变化前的值：${oldVal}`);
})
deep: true 深度侦听整个对象  immediate: true: 立即侦听
watch(user, (newVal, oldVal) => {
  console.log(newVal);
}, {deep: true, immediate: true})
 */

// watch 侦听date数组
watch(() => searchEmp.value.entryDate, (newVal, oldVal) => {
  if(newVal && newVal.length == 2) {
    searchEmp.value.begin = newVal[0]
    searchEmp.value.end = newVal[1]
  } else {
    searchEmp.value.begin = ''
    searchEmp.value.end = ''
  }
})

/* 表格数据模型 */
const empList = ref([])

/* 分页条数据 */
const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(true)
const disabled = ref(false)
const total = ref(100)

const handleSizeChange = (val) => {
  search()
}
const handleCurrentChange = (val) => {
  search()
}

/* 条件分页查询 */
const search = async () => {
  const result = await queryAllApi(searchEmp.value.name, searchEmp.value.gender, 
              searchEmp.value.begin, searchEmp.value.end, currentPage.value, pageSize.value)
  if(result.code) {
    // 请求成功
    total.value = result.data.total
    empList.value = result.data.rows
  }
}

// 清空搜索条件
const clear = () => {
  searchEmp.value = {
    name: '',
    gender: '',
    entryDate: [],
    begin: '',
    end: ''
  },
  search()
}

// 添加、修改员工对话框
// 新增/修改表单
const employee = ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: []
})

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref()

//文件上传
// 图片上传成功后触发
const handleAvatarSuccess = (response) => {
  employee.value.image = response.data
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}

// 点击新增员工
const addEmp = () => {
  dialogVisible.value = true
  // 清空表单
  employee.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: []
  },
  // 设置对话框标题
  dialogTitle.value = '新增员工'
  // 清空表单中的校验规则
  if (empRuleRef.value) {
    empRuleRef.value.resetFields();
  }
}

// 职位列表数据
const jobs = ref([{ name: '班主任', value: 1 },{ name: '讲师', value: 2 },{ name: '学工主管', value: 3 },{ name: '教研主管', value: 4 },{ name: '咨询师', value: 5 },{ name: '其他', value: 6 }])
// 性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])

// 点击添加工作经历
const addExpr = () => {
  // 往工作经历数组中添加一条数据
  employee.value.exprList.push({company: '', job: '', begin: '', end: '', entryDate: []})
}

// 点击删除工作经历
const delExprItem = (index) => {
  // 从数组中删除index位置的对象
  employee.value.exprList.splice(index, 1)
}

// 表单引用
const empRuleRef = ref()
// 点击保存按钮保存员工
const save = async () => {
  if (!empRuleRef.value) return;
  // 对表单进行校验
  empRuleRef.value.validate(async (valid) => {
    if (valid) {
      // 表单校验通过
      let result;
      // 根据有没有id判断是新增还是修改
      if(employee.value.id) {
        // 修改
        result = await updateApi(employee.value)
      } else {
        // 新增
        result = await saveApi(employee.value)
      }
      
      // 判断是否保存成功
      if(result.code) {
        // 关闭对话框
        dialogVisible.value = false
        // 提示保存成功
        ElMessage.success('操作成功')
        // 重新查询列表数据
        search()
      } else {
        ElMessage.error('操作失败')
      }
    } else {
      // 表单校验失败
      ElMessage.error("表单校验失败");
    }
  })
}

// 表单校验规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ]
});

// 点击编辑按钮
const edit = async (id) => {
  // 1.设置对话框标题
  dialogTitle.value = '修改员工'
  // 2.打开弹窗
  dialogVisible.value = true
  // 3.查询这条记录的数据并回显
  const result = await queryByIdApi(id)
  if(result.code) {
    employee.value = result.data
    // 获取到工作经历集合，并判断是否为空
    const exprList = employee.value.exprList
    if(exprList && exprList.length > 0) {
      // 遍历
      exprList.forEach(expr => {
        expr.entryDate = [expr.begin, expr.end]
      })
    }
  }
  // 4.清空表单校验
  if (empRuleRef.value) {
    empRuleRef.value.resetFields();
  }
}

// 获取批量删除时选中的行的id数组
const selectedIds = ref([])
const handleSelectionChange = (val) => {
  selectedIds.value = val.map((row) => {
    return row.id
  })
  console.log(selectedIds.value);
}

// 点击批量删除
const batchDeleteEmp = () => {
  // 1.获取到复选框勾选的记录的id
  if(!(selectedIds && selectedIds.value.length > 0)) {
    ElMessage.warning('您没有选择任何要删除的数据')
    return
  }
  // 2.弹出一个确认对话框
  // 弹出一个确认框
  ElMessageBox.confirm(
    "您确定要删除选中的记录吗？",
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
      // 调用方法删除这条数据
      const result = await deleteApi(selectedIds.value)
      if(result.code) {
        // 重新查询列表数据
        search()
        ElMessage.success("删除成功")
      } else {
        ElMessage.error(result.msg)
      }
    })
    .catch(() => {
      ElMessage.info("取消删除")
    });
}

// 删除单条记录
const deleteById = (id) => {
  selectedIds.value = [id]
  batchDeleteEmp()
}

/* 侦听工作经历数组 */
watch(() => employee.value.exprList, (newVal, oldVal) => {
  if(employee.value.exprList && employee.value.exprList.length > 0) {
    employee.value.exprList.forEach(expr => {
      if(expr.entryDate && expr.entryDate.length > 0) {
        expr.begin = expr.entryDate[0]
        expr.end = expr.entryDate[1]
      }
    });
  }
}, {deep: true})

const token = ref('')
const depts = ref([])
onMounted(async () => {
  search()
  const result = await queryAllDeptApi()
  depts.value = result.data
  const loginUser = JSON.parse(localStorage.getItem('loginUser'))
  token.value = loginUser.token
})
</script>

<template>
  <h1>员工管理</h1><br>
  <!-- 搜索表单 -->
  <el-form :inline="true" :model="searchEmp" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchEmp.name" placeholder="请输入员工姓名" clearable />
    </el-form-item>
    <el-form-item label="性别">
      <el-select
        v-model="searchEmp.gender"
        placeholder="请选择"
        clearable
      >
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职时间">
      <el-date-picker
        v-model="searchEmp.entryDate"
        type="daterange"
        value-format="YYYY-MM-DD"
        range-separator="到"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="shortcuts"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  <!-- 两个按钮 -->
  <el-button type="primary" @click="addEmp">+ 新增员工</el-button>
  <el-button type="danger" @click="batchDeleteEmp">- 批量删除</el-button>
  <br> <br>
  <!-- 数据展示表格 -->
  <el-table :data="empList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" align="center"/>
    <el-table-column prop="name" label="姓名" width="180"  align="center"/>
    <el-table-column label="性别" align="center"  width="100">
      <template #default="scope">
        {{ scope.row.gender == 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column label="头像"  align="center"  width="150">
      <template #default="scope">
        <img :src="scope.row.image" height="50px">
      </template>
    </el-table-column>
    <el-table-column prop="deptName" label="所属部门"  align="center"/>
    <el-table-column prop="job" label="职位"  align="center">
      <template #default="scope">
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else>咨询师</span>
      </template>
    </el-table-column>
    <el-table-column prop="entryDate" label="入职日期"  align="center"/>
    <el-table-column prop="updateTime" label="最后操作时间"  align="center"/>
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>
  <!-- 分页条 -->
  <div style="float: right;">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :disabled="disabled"
      :background="background"
      layout="sizes, total, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增/修改员工的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="employee" :rules="rules" ref="empRuleRef" label-width="80px">
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="employee.username" placeholder="请输入员工用户名，2-20个字"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="employee.name" placeholder="请输入员工姓名，2-10个字"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="employee.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for="gender in genders" :key="gender.value" :label="gender.name" :value="gender.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="employee.phone" placeholder="请输入员工手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位">
              <el-select v-model="employee.job" placeholder="请选择职位" style="width: 100%;">
                <el-option v-for="job in jobs" :key="job.value" :label="job.name" :value="job.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资">
              <el-input v-model="employee.salary" placeholder="请输入员工薪资"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门">
              <el-select v-model="employee.deptId" placeholder="请选择部门" style="width: 100%;">
                <el-option v-for="dept in depts" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期">
              <el-date-picker v-model="employee.entryDate" type="date" style="width: 100%;" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :headers="{'Token': token}"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                >
                <img v-if="employee.image" :src="employee.image" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 工作经历 -->
        <!-- 第六行 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="工作经历">
              <el-button type="success" size="small" @click="addExpr">+ 添加工作经历</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第七行 ...  工作经历 -->
        <el-row v-for="(expr, index) in employee.exprList" :key="index" :gutter="3">
          <el-col :span="10">
            <el-form-item size="small" label="时间" label-width="80px">
              <el-date-picker type="daterange" v-model="expr.entryDate" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item size="small" label="公司" label-width="60px">
              <el-input placeholder="请输入公司名称" v-model="expr.company"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item size="small" label="职位" label-width="60px">
              <el-input placeholder="请输入职位" v-model="expr.job"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="2">
            <el-form-item size="small" label-width="0px">
              <el-button type="danger" @click="delExprItem(index)" >- 删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
  </el-dialog>
</template>

<style scoped>
.avatar {
  height: 40px;
}
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  border-radius: 10px;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>